package com.zmx.doctor.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddTripActivity extends BaseActivity {

    @BindView(R.id.content)
    EditText content;
    @BindView(R.id.start_date)
    TextView startDate;
    @BindView(R.id.start_time)
    TextView startTime;
    @BindView(R.id.end_date)
    TextView endDate;
    @BindView(R.id.end_time)
    TextView endTime;
    @BindView(R.id.regular)
    TextView regular;
    @BindView(R.id.notice)
    TextView notice;
    @BindView(R.id.save)
    Button save;

    private String end_date = "";
    private String end_time = "";
    private String start_date = "";
    private String start_time = "";

    private Calendar calendar = Calendar.getInstance(Locale.CHINA);


    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_trip;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);


    }

    /**
     * 日期选择
     *
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar, int logo) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "/" + (monthOfYear + 1) + "/" + dayOfMonth);

                if (logo == 1) {

                    start_date = tv.getText().toString();

                } else {
                    end_date = tv.getText().toString();
                }

            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    /**
     * 时间选择
     *
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public void showTimePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar, int logo) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog(activity, themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(hourOfDay + ":" + minute);
                        if (logo == 1) {

                            start_time = tv.getText().toString();

                        } else {
                            end_time = tv.getText().toString();
                        }
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                , true).show();
    }


    @OnClick({R.id.start_date, R.id.start_time, R.id.end_date, R.id.end_time, R.id.regular, R.id.notice, R.id.save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.start_date:

                showDatePickerDialog(this, 4, startDate, calendar, 1);

                break;
            case R.id.start_time:
                showTimePickerDialog(this, 4, startTime, calendar, 1);
                break;
            case R.id.end_date:

                showDatePickerDialog(this, 4, endDate, calendar, 2);
                break;
            case R.id.end_time:
                showTimePickerDialog(this, 4, endTime, calendar, 2);
                break;
            case R.id.regular:
                showList();
                break;
            case R.id.notice:
                showNotice();
                break;
            case R.id.save:

                if (end_date.equals("")) {
                    Toast("请选择结束日期");
                    return;
                }
                if (end_time.equals("")) {
                    Toast("请选择结束时间");
                    return;
                }
                if (start_date.equals("")) {
                    Toast("请选择开始日期");
                    return;
                }
                if (start_time.equals("")) {
                    Toast("请选择开始时间");
                    return;
                }
                if (content.getText().toString().equals("")){
                    Toast("请输入内容");
                    return;
                }
                if (content.getText().toString().equals("")){
                    Toast("请输入内容");
                    return;
                }
                addSchedule();
                break;
        }
    }

    private AlertDialog alertDialog1; //信息框

    public void showList() {

        final String[] items = {"每天", "只响一次", "周一至周五"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle("请选择");
        alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                regular.setText(items[i]);
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = alertBuilder.create();
        alertDialog1.show();
    }

    public void showNotice() {
        final String[] items = {"10分钟前", "无提示", "一小时"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle("请选择");
        alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                notice.setText(items[i]);
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = alertBuilder.create();
        alertDialog1.show();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1){

                            finish();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };


    public void addSchedule() {
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        List<String> l = new ArrayList<>();
        l.add(sdFormatter.format(new Date()));
        l.add(end_date+" "+end_time);
        l.add(start_date+" "+start_time);
        l.add(content.getText().toString());
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "addSchedule");
        params.put("data[starttime]", start_date+" "+start_time);
        params.put("data[endtime]", end_date+" "+end_time);
        params.put("data[advatime]", sdFormatter.format(new Date()));
        params.put("data[title]", content.getText().toString());
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 1, 404);

    }

}
